package com.ruoyi.project.system.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SmPay;
import com.ruoyi.project.system.domain.SmRefund;
import com.ruoyi.project.system.mapper.SmPayMapper;
import com.ruoyi.project.system.mapper.SmRefundMapper;
import com.ruoyi.project.system.service.ISmIncomeService;
import com.ruoyi.project.system.service.ISmRefundService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.ruoyi.common.utils.AlibabaApi.refund;
import static com.ruoyi.common.utils.uuid.Seq.getRefundNo;
import static com.ruoyi.framework.web.domain.AjaxResult.error;
import static com.ruoyi.framework.web.domain.AjaxResult.success;

/**
 * 退款Service业务层处理
 */
@Service
public class SmRefundServiceImpl implements ISmRefundService {

    @Autowired
    private ISmIncomeService iSmIncomeService;

    @Autowired
    private SmPayMapper smPayMapper;

    @Autowired
    private SmRefundMapper smRefundMapper;

    @Override
    @Transactional
    public AjaxResult insertSmRefund(SmPay smPay) throws AlipayApiException {
        // 1. 支付订单退款
        smPayMapper.updateSmPay(new SmPay(smPay.getId(), "REFUND"));
        // 2. 收益订单退款
        iSmIncomeService.inComeRefund(smPay);
        // 3. 创建退款单
        smPay.setRemark(getRefundNo());

        SmRefund smRefund = new SmRefund(smPay.getId(), smPay.getRemark(), smPay.getPricing());
        smRefundMapper.insertSmRefund(smRefund);
        // 4. 调用支付接口退款
        try {
            AlipayTradeRefundResponse response = refund(smPay);
            if ("10000".equals(response.getCode())) {
                smRefundMapper.updateSmRefund_(smRefund.getId(), response.getMsg(), response.getOutTradeNo());
                return success();
            }
            smRefundMapper.updateSmRefund(smRefund.getId(), response.getMsg());
            return error(response.getMsg());
        } catch (Exception e) {
            smRefundMapper.updateSmRefund(smRefund.getId(), e.getMessage());
            return error(e.getMessage());
        }
    }

    @Override
    public int deleteSmRefundByIds(Integer[] ids) {
        return 0;
    }

    /**
     * 查询退款
     *
     * @param id 退款主键
     * @return 退款
     */
    @Override
    public SmRefund selectSmRefundById(Integer id) {
        return smRefundMapper.selectSmRefundById(id);
    }

    /**
     * 查询退款列表
     *
     * @param smRefund 退款
     * @return 退款
     */
    @Override
    public List<SmRefund> selectSmRefundList(SmRefund smRefund) {
        return smRefundMapper.selectSmRefundList(smRefund);
    }

}
